﻿using System;
using System.ServiceModel.Channels;
using CoreEx.Wcf.Common.Implementation.Compression;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;

namespace CoreEx.Wcf.Common.Implementation.Compression
{
    [Implements(typeof(MessageEncoderFactory))]
    public class CustomEncoderFactory : MessageEncoderFactory, IInitialize
    {        
        private MessageEncoder _encoder;

        private MessageEncoderFactory _innerMessageEncoderFactory;


        /// <summary>
        /// Initializes a new instance of the <see cref="CustomEncoderFactory"/> class.
        /// </summary>
        /// <param name="innerMessageEncoderFactory">The inner message encoder factory.</param>
        public CustomEncoderFactory(MessageEncoderFactory innerMessageEncoderFactory)
        {
            _innerMessageEncoderFactory = innerMessageEncoderFactory;
        }


        /// <summary>
        /// When overridden in a derived class, gets the message encoder that is produced by the factory.
        /// </summary>
        /// <returns>
        /// The <see cref="T:System.ServiceModel.Channels.MessageEncoder"/> used by the factory.
        /// </returns>
        public override MessageEncoder Encoder
        {
            get { return _encoder; }
        }

        /// <summary>
        /// When overridden in a derived class, gets the message version that is used by the encoders produced by the factory to encode messages.
        /// </summary>
        /// <returns>
        /// The <see cref="T:System.ServiceModel.Channels.MessageVersion"/> used by the factory.
        /// </returns>
        public override MessageVersion MessageVersion
        {
            get { return _encoder.MessageVersion; }
        }
       
        public void Initialize(IServiceContainer source)
        {
            var innerEncoder = _innerMessageEncoderFactory.Encoder;            
            _encoder = source.GetService<MessageEncoder>(innerEncoder);            
        }
    }
}